//
//  MTzkCityListVC.m
//  maTuanWang
//
//  Created by 帮友贷 on 16/3/7.
//  Copyright © 2016年 帮友贷. All rights reserved.
//

#import "MTzkCityListVC.h"
#import "ZKCity.h"
#import "ZKcityModle.h"
#import "ZKTheCollectionViewCell.h"
#import "ZKCollectionView.h"
#import "ZKcollectionCell.h"

#import <CoreLocation/CoreLocation.h>
//
@interface MTzkCityListVC ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,CLLocationManagerDelegate>
{
    ZKCollectionView * collectionView;
}

@property (strong, nonatomic) IBOutlet UITableView *zkCityTabel;
/** 城市数组 */
@property (nonatomic ,strong) NSArray * cityGroups;

/** 热门城市 */
@property (nonatomic ,strong) NSArray * hotCitys;

/** 位置管理者 */
@property (nonatomic, strong) CLLocationManager  *locationManager;

/** 地理编码 */
@property (nonatomic, strong) CLGeocoder *geoC;
@end

@implementation MTzkCityListVC

static NSString * const zkCollectionID = @"collectionCell";


- (CLLocationManager *)locationManager
{
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc]init];
        _locationManager.delegate = self;
        
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
            [_locationManager requestWhenInUseAuthorization];
        }
    }
    return _locationManager;
}

- (CLGeocoder *)geoC
{
    if (!_geoC) {
        _geoC = [[CLGeocoder alloc] init];
    }
    return _geoC;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    // 开始定位
//    [self.locationManager startUpdatingLocation];
    
    [self setUpView];
    
    [self setUpCollection];
    
    [self setUpLocation];
    // 开始定位
    [self.locationManager startUpdatingLocation];
}

-(void)setUpLocation
{
    //    [self.locationManager startUpdatingLocation];
    
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    // 2.判断用户是否授权
    if (status == kCLAuthorizationStatusNotDetermined) {
        NSLog(@"等待用户授权");
    }else if (status == kCLAuthorizationStatusAuthorizedAlways ||
              status == kCLAuthorizationStatusAuthorizedWhenInUse)
    {
        NSLog(@"授权成功");
        _locationManager.distanceFilter = 10;
        _locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    } else {
        NSLog(@"授权失败");
    }
}
/**
 *
 */
-(void)setUpView{
//    [self setAutomaticallyAdjustsScrollViewInsets:YES];
    
    self.zkCityTabel.sectionIndexColor = [UIColor colorWithRed:18.0f/255.0f green:235.0f/255.0f blue:154.0f/255.0f alpha:1];
    self.zkCityTabel.sectionIndexBackgroundColor = [UIColor clearColor];
}

-(void)setUpCollection{
    collectionView = [ZKCollectionView theCollectionView];
    collectionView.theCollectionView.delegate = self;
    collectionView.theCollectionView.dataSource = self;
    
    [collectionView.theCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([ZKTheCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:zkCollectionID];
    
    collectionView.theCollectionView.backgroundColor = [UIColor whiteColor];
    
    _hotCitys = @[@"北京市",@"天津市",@"上海市",@"深圳市",@"广州市",@"重庆市",@"武汉市",@"青岛市",@"济南市"];
}

#pragma mark CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    [self.locationManager stopUpdatingLocation];
    CLLocation *currLocation=[locations lastObject];
    double theLatitude = currLocation.coordinate.latitude;
    double theLongitude = currLocation.coordinate.longitude;
    
    CLLocation *loc = [[CLLocation alloc] initWithLatitude:theLatitude longitude:theLongitude];
    [self.geoC reverseGeocodeLocation:loc completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if(error == nil)
        {
            [placemarks enumerateObjectsUsingBlock:^(CLPlacemark * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                self.locationCityName = obj.locality;
            }];
        }else
        {
            self.locationCityName = @"定位失败";
        }
        
        
        [self.zkCityTabel reloadData];
//        self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"home-dingwei" highImage:nil titleString:locationCityName titleColor:(UIColor *)MTRGBColor(35, 167, 241) leftOrRight:(BOOL)YES target:self action:@selector(leftBtnClick)];
        
    }];
}



-(NSArray *)cityGroups
{
    if (_cityGroups == nil) {
        _cityGroups = [ZKcityModle cityGroups];
    }
    
    return _cityGroups;
}

#pragma mark tableView delegate

// 分组总数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.cityGroups.count+2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section < 2) {
        return 1;
    } else {
        ZKcityModle * cityModel = self.cityGroups[section-2];
        
        return cityModel.citys.count;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 44;
    } else if (indexPath.section == 1) {
        return 120;
    } else {
        return 44;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1f;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        static NSString * ID = @"head";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        cell.textLabel.text = self.locationCityName;
        return cell;
        
    } else if (indexPath.section == 1) {
        
        ZKcollectionCell * cell = [ZKcollectionCell theDetailViewCell:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        //        collectionView.frame = CGRectMake(0, 0, cell.cellBgView.frame.size.width, 120);
        
        collectionView.frame = cell.contentView.frame;
        [cell.cellBgView addSubview:collectionView];
        
        //        NSLog(@"%@",collectionView);
        //        [cell.contentView addSubview:collectionView];
        
        return cell;
        
    } else {
        static NSString * ID = @"cell";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        
        // 设置cell内容
        // 1> 取出数据模型
        ZKcityModle *group = self.cityGroups[indexPath.section-2];
        ZKCity * city = group.citys[indexPath.row];
        
        cell.textLabel.text = city.city_name;
        
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cityName;
    if (indexPath.section == 0) {
        [self.delegate theChoiseCity:self.locationCityName];
        cityName = self.locationCityName;
    } else if (indexPath.section == 1) {
        
    } else {
        ZKcityModle *group = self.cityGroups[indexPath.section-2];
        ZKCity * city = group.citys[indexPath.row];
        
        cityName = city.city_name;
//        cell.textLabel.text = city.city_name;
        
    }
    
    [self.delegate theChoiseCity:cityName];

    [self.navigationController popViewControllerAnimated:YES];
}


// 标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @"⭐️";
    } else if (section == 1) {
        return @"🔥";
    } else {
        // 找到group
        ZKcityModle *group = self.cityGroups[section-2];
        
        return group.titleName;
    }
}

-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray * arr = [[NSMutableArray alloc]init];
    
    [arr addObject:@"⭐️"];
    [arr addObject:@"🔥"];
    [arr addObjectsFromArray:[self.cityGroups valueForKeyPath:@"titleName"]];
    
    return arr;
}

#pragma mark collectionView delegate

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//多少行
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.hotCitys.count;
}

//每行显示什么（每行并不是一行，而是一个cell）
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //    static NSString *iden = @"pp";
    
    ZKTheCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:zkCollectionID forIndexPath:indexPath];
    
    cell.cityLabel.text = self.hotCitys[indexPath.row];
    
    return cell;
}


//点击
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * cityName = self.hotCitys[indexPath.row];

    [self.delegate theChoiseCity:cityName];
    
    [self.navigationController popViewControllerAnimated:YES];
//    if (indexPath.row == 9) {
//        self.tabBarController.selectedIndex = 2;
//
//    }else{
//        [self.navigationController pushViewController:arr[indexPath.row] animated:YES];
//
//    }
}

//设置每个cell大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake([UIScreen mainScreen].bounds.size.width/3-30, 26);
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}
//
////段头段尾
//-(UICollectionReusableView*)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
//{
//    if(kind == UICollectionElementKindSectionHeader){
//
//
//        //段头
//        header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"head" forIndexPath:indexPath];
//
//        UIButton * btn1 = (UIButton *)[header.view2 viewWithTag:4444];
//        [btn1 addTarget:self action:@selector(payIn:) forControlEvents:UIControlEventTouchUpInside];
//
//        UIButton * btn2 = (UIButton *)[header.view2 viewWithTag:4445];
//        [btn2 addTarget:self action:@selector(payOut:) forControlEvents:UIControlEventTouchUpInside];
//
//        UIButton * btn3 = (UIButton *)[header.view1 viewWithTag:4446];
//        [btn3 addTarget:self action:@selector(leftBtn:) forControlEvents:UIControlEventTouchUpInside];
//
//        UIButton * btn4 = (UIButton *)[header.view1 viewWithTag:4447];
//        [btn4 addTarget:self action:@selector(rightBtn:) forControlEvents:UIControlEventTouchUpInside];
//
//        return header;
//    }else{
//        return nil;
//    }
//}


@end
